<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>commonevent、eventhub、emitter和worker使用 | East'blog</title><meta name="author" content="侯玉东"><meta name="copyright" content="侯玉东"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="commonevent、eventhub、emitter和worker使用">
<meta property="og:type" content="article">
<meta property="og:title" content="commonevent、eventhub、emitter和worker使用">
<meta property="og:url" content="https://houyudong1989.gitee.io/blog/2024/03/25/harmonyOS/commonevent%E3%80%81eventhub%E3%80%81emitter%E5%92%8Cworker%E4%BD%BF%E7%94%A8/index.html">
<meta property="og:site_name" content="East&#39;blog">
<meta property="og:description" content="commonevent、eventhub、emitter和worker使用">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://houyudong1989.gitee.io/blog/img/library1.jpeg">
<meta property="article:published_time" content="2024-03-25T02:52:56.680Z">
<meta property="article:modified_time" content="2024-03-26T09:33:33.630Z">
<meta property="article:author" content="侯玉东">
<meta property="article:tag" content="harmonyOS">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://houyudong1989.gitee.io/blog/img/library1.jpeg"><link rel="shortcut icon" href="/blog/img/head.jpg"><link rel="canonical" href="https://houyudong1989.gitee.io/blog/2024/03/25/harmonyOS/commonevent%E3%80%81eventhub%E3%80%81emitter%E5%92%8Cworker%E4%BD%BF%E7%94%A8/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/blog/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/blog/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  infinitegrid: {
    js: 'https://cdn.jsdelivr.net/npm/@egjs/infinitegrid/dist/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'commonevent、eventhub、emitter和worker使用',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2024-03-26 17:33:33'
}</script><script>(win=>{
      win.saveToLocal = {
        set: (key, value, ttl) => {
          if (ttl === 0) return
          const now = Date.now()
          const expiry = now + ttl * 86400000
          const item = {
            value,
            expiry
          }
          localStorage.setItem(key, JSON.stringify(item))
        },
      
        get: key => {
          const itemStr = localStorage.getItem(key)
      
          if (!itemStr) {
            return undefined
          }
          const item = JSON.parse(itemStr)
          const now = Date.now()
      
          if (now > item.expiry) {
            localStorage.removeItem(key)
            return undefined
          }
          return item.value
        }
      }
    
      win.getScript = (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        script.onerror = reject
        script.onload = script.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          script.onload = script.onreadystatechange = null
          resolve()
        }

        Object.keys(attr).forEach(key => {
          script.setAttribute(key, attr[key])
        })

        document.head.appendChild(script)
      })
    
      win.getCSS = (url, id = false) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onerror = reject
        link.onload = link.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          link.onload = link.onreadystatechange = null
          resolve()
        }
        document.head.appendChild(link)
      })
    
      win.activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
        if (t === 'dark') activateDarkMode()
        else if (t === 'light') activateLightMode()
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
      const detectApple = () => {
        if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
          document.documentElement.classList.add('apple')
        }
      }
      detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>(()=>{
  const $loadingBox = document.getElementById('loading-box')
  const $body = document.body
  const preloader = {
    endLoading: () => {
      $body.style.overflow = ''
      $loadingBox.classList.add('loaded')
    },
    initLoading: () => {
      $body.style.overflow = 'hidden'
      $loadingBox.classList.remove('loaded')
    }
  }

  preloader.initLoading()
  window.addEventListener('load',() => { preloader.endLoading() })

  if (true) {
    document.addEventListener('pjax:send', () => { preloader.initLoading() })
    document.addEventListener('pjax:complete', () => { preloader.endLoading() })
  }
})()</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/blog/img/head.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">70</div></a><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">26</div></a><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">18</div></a></div><hr class="custom-hr"/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/blog/link/"><i class="fa-fw fas fa-link"></i><span> 友联</span></a></div><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg fixed" id="page-header" style="background-image: url('/blog/img/library4.jpeg')"><nav id="nav"><span id="blog-info"><a href="/blog/" title="East'blog"><img class="site-icon" src="/blog/img/head.jpg"/><span class="site-name">East'blog</span></a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/blog/link/"><i class="fa-fw fas fa-link"></i><span> 友联</span></a></div><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">commonevent、eventhub、emitter和worker使用</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2024-03-25T02:52:56.680Z" title="发表于 2024-03-25 10:52:56">2024-03-25</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2024-03-26T09:33:33.630Z" title="更新于 2024-03-26 17:33:33">2024-03-26</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/harmonyOS/">harmonyOS</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="commonevent、eventhub、emitter和worker使用"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><p><a target="_blank" rel="noopener" href="https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V2/uiability-data-sync-with-ui-0000001427744556-V2">https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V2/uiability-data-sync-with-ui-0000001427744556-V2</a></p>
<h1 id="CES-common-event-service（公共事件服务）进程间通信"><a href="#CES-common-event-service（公共事件服务）进程间通信" class="headerlink" title="CES common event service（公共事件服务）进程间通信"></a>CES common event service（公共事件服务）进程间通信</h1><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">公共事件从系统角度可分为：系统公共事件和自定义公共事件。系统公共事件由系统应用和系统服务进行发布，如安装、更新、卸载等公共事件。自定义公共事件用来实现跨进程通信能力。</span><br></pre></td></tr></table></figure>

<ul>
<li>api9使用会报错，提示找不到，要使用api10才行</li>
</ul>
<h2 id="示意图"><a href="#示意图" class="headerlink" title="示意图"></a>示意图</h2><p><img src="https://alliance-communityfile-drcn.dbankcdn.com/FileServer/getFile/cmtyPub/011/111/111/0000000000011111111.20240320153822.99872633347954331552351973256199:50001231000000:2800:244255802CB341E64061AEB8EE983A453184D1BE4C4CD609CF0FBDFC8C2CE57A.png?needInitFileName=true?needInitFileName=true"></p>
<h2 id="公共事件类型"><a href="#公共事件类型" class="headerlink" title="公共事件类型"></a>公共事件类型</h2><h3 id="无序公共事件"><a href="#无序公共事件" class="headerlink" title="无序公共事件"></a>无序公共事件</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">CES转发公共事件时，不考虑订阅者是否接收到，且订阅者接收到的顺序与其订阅顺序无关。</span><br></pre></td></tr></table></figure>

<h3 id="有序公共事件"><a href="#有序公共事件" class="headerlink" title="有序公共事件"></a>有序公共事件</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">CES转发公共事件时，根据订阅者设置的优先级等级，优先将公共事件发送给优先级较高的订阅者，等待其成功接收该公共事件之后再将事件发送给优先级较低的订阅者。如果有多个订阅者具有相同的优先级，则他们将随机接收到公共事件。</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="粘性公共事件"><a href="#粘性公共事件" class="headerlink" title="粘性公共事件"></a>粘性公共事件</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">能够让订阅者收到在订阅前已经发送的公共事件就是粘性公共事件。普通的公共事件只能在订阅后发送才能收到，而粘性公共事件的特殊性就是可以先发送后订阅。发送粘性事件必须是系统应用或系统服务，且需要申请ohos.permission.COMMONEVENT_STICKY权限</span><br></pre></td></tr></table></figure>

<h2 id="公共事件发布"><a href="#公共事件发布" class="headerlink" title="公共事件发布"></a>公共事件发布</h2><figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> commonEventManager <span class="keyword">from</span> <span class="string">&#x27;@ohos.commonEventManager&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 公共事件相关信息</span></span><br><span class="line"><span class="keyword">let</span> options = &#123;</span><br><span class="line">    <span class="attr">code</span>: <span class="number">1</span>, <span class="comment">// 公共事件的初始代码</span></span><br><span class="line">    <span class="attr">data</span>: <span class="string">&quot;initial data&quot;</span>, <span class="comment">// 公共事件的初始数据</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 发布公共事件  options为可选参数，如果发布事件不需要携带参数可以不传</span></span><br><span class="line">commonEventManager.<span class="title function_">publish</span>(<span class="string">&quot;custom_event&quot;</span>, options, <span class="function">(<span class="params">err</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (err) &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">error</span>(<span class="string">&#x27;[CommonEvent] PublishCallBack err=&#x27;</span> + <span class="title class_">JSON</span>.<span class="title function_">stringify</span>(err));</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">info</span>(<span class="string">&#x27;[CommonEvent] Publish success&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h2 id="公共事件订阅和取消"><a href="#公共事件订阅和取消" class="headerlink" title="公共事件订阅和取消"></a>公共事件订阅和取消</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">公共事件订阅和取消订阅步骤，分别是：</span><br><span class="line">1、导入模块</span><br><span class="line">2、创建订阅者信息，订阅何种事件</span><br><span class="line">3、创建订阅者，用于执行订阅、退订操作</span><br><span class="line">4、创建订阅回调函数</span><br><span class="line">5、取消订阅事件</span><br></pre></td></tr></table></figure>

<h3 id="导入模块"><a href="#导入模块" class="headerlink" title="导入模块"></a>导入模块</h3><figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> commonEventManager <span class="keyword">from</span> <span class="string">&#x27;@ohos.commonEventManager&#x27;</span>; </span><br><span class="line"><span class="keyword">import</span> <span class="title class_">Base</span> <span class="keyword">from</span> <span class="string">&#x27;@ohos.base&#x27;</span>;</span><br></pre></td></tr></table></figure>

<h3 id="创建订阅者信息，订阅何种事件"><a href="#创建订阅者信息，订阅何种事件" class="headerlink" title="创建订阅者信息，订阅何种事件"></a>创建订阅者信息，订阅何种事件</h3><figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 订阅者信息</span></span><br><span class="line"><span class="keyword">let</span> <span class="attr">subscribeInfo</span>: commonEventManager.<span class="property">CommonEventSubscribeInfo</span> = &#123;</span><br><span class="line">  <span class="attr">events</span>: [<span class="string">&quot;usual.event.SCREEN_OFF&quot;</span>], <span class="comment">// 订阅灭屏公共事件</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="创建订阅者，用于执行订阅、退订操作"><a href="#创建订阅者，用于执行订阅、退订操作" class="headerlink" title="创建订阅者，用于执行订阅、退订操作"></a>创建订阅者，用于执行订阅、退订操作</h3><figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 用于保存创建成功的订阅者对象，后续使用其完成订阅及退订的动作</span></span><br><span class="line"><span class="keyword">let</span> <span class="attr">subscriber</span>: commonEventManager.<span class="property">CommonEventSubscriber</span> | <span class="literal">null</span> = <span class="literal">null</span>;</span><br><span class="line"><span class="comment">// 创建订阅者回调</span></span><br><span class="line">commonEventManager.<span class="title function_">createSubscriber</span>(subscribeInfo, <span class="function">(<span class="params">err: Base.BusinessError, data: commonEventManager.CommonEventSubscriber</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">if</span> (err) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">error</span>(<span class="string">`Failed to create subscriber. Code is <span class="subst">$&#123;err.code&#125;</span>, message is <span class="subst">$&#123;err.message&#125;</span>`</span>);</span><br><span class="line">    <span class="keyword">return</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">info</span>(<span class="string">&#x27;Succeeded in creating subscriber.&#x27;</span>);</span><br><span class="line">  subscriber = data;</span><br><span class="line">  <span class="comment">// 订阅公共事件回调</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h3 id="创建订阅回调函数"><a href="#创建订阅回调函数" class="headerlink" title="创建订阅回调函数"></a>创建订阅回调函数</h3><figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 订阅公共事件回调</span></span><br><span class="line"><span class="keyword">if</span> (subscriber !== <span class="literal">null</span>) &#123;</span><br><span class="line">  commonEventManager.<span class="title function_">subscribe</span>(subscriber, <span class="function">(<span class="params">err: Base.BusinessError, data: commonEventManager.CommonEventData</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (err) &#123;</span><br><span class="line">      <span class="variable language_">console</span>.<span class="title function_">error</span>(<span class="string">`Failed to subscribe common event. Code is <span class="subst">$&#123;err.code&#125;</span>, message is <span class="subst">$&#123;err.message&#125;</span>`</span>);</span><br><span class="line">      <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;)</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">error</span>(<span class="string">`Need create subscriber`</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="取消订阅事件"><a href="#取消订阅事件" class="headerlink" title="取消订阅事件"></a>取消订阅事件</h3><figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// subscriber为订阅事件时创建的订阅者对象</span></span><br><span class="line"><span class="keyword">if</span> (subscriber !== <span class="literal">null</span>) &#123;</span><br><span class="line">    commonEventManager.<span class="title function_">unsubscribe</span>(subscriber, <span class="function">(<span class="params">err</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (err) &#123;</span><br><span class="line">            <span class="variable language_">console</span>.<span class="title function_">error</span>(<span class="string">`[CommonEvent] UnsubscribeCallBack err=<span class="subst">$&#123;<span class="built_in">JSON</span>.stringify(err)&#125;</span>`</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="variable language_">console</span>.<span class="title function_">info</span>(<span class="string">`[CommonEvent] Unsubscribe`</span>);</span><br><span class="line">            subscriber = <span class="literal">null</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="线程间通信-emitter-和-worker"><a href="#线程间通信-emitter-和-worker" class="headerlink" title="线程间通信 emitter 和 worker"></a>线程间通信 emitter 和 worker</h1><figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">harmonyOS应用中每个进程都会有一个主线程，和最多<span class="number">8</span>个worker工作线程</span><br><span class="line">主线程有以下职责：</span><br><span class="line">    <span class="number">1</span>、执行<span class="variable constant_">UI</span>绘制。</span><br><span class="line">    <span class="number">2</span>、管理主线程的<span class="title class_">ArkTS</span>引擎实例，使多个<span class="title class_">UIAbility</span>组件能够运行在其之上。</span><br><span class="line">    <span class="number">3</span>、管理其他线程(例如worker线程)的<span class="title class_">ArkTS</span>引擎实例，例如启动和终止其他线程。</span><br><span class="line">    <span class="number">4</span>、分发交互事件。</span><br><span class="line">    <span class="number">5</span>、处理应用代码的回调，包括事件处理和生命周期管理。</span><br><span class="line">    <span class="number">6</span>、接收worker线程发送的消息。</span><br><span class="line">工作线程职责：</span><br><span class="line">    执行好事操作，但不可以直接操作<span class="variable constant_">UI</span>。</span><br><span class="line">基于<span class="title class_">HarmonyOS</span>的线程模型，不同的业务功能运行在不同的线程上，业务功能的交互就需要线程间通信。线程间通信目前主要有<span class="title class_">Emitter</span>和<span class="title class_">Worker</span>两种方式，其中<span class="title class_">Emitter</span>主要适用于线程间的事件同步， <span class="title class_">Worker</span>主要用于新开一个线程执行耗时任务。</span><br></pre></td></tr></table></figure>

<h2 id="emitter-线程间通信"><a href="#emitter-线程间通信" class="headerlink" title="emitter 线程间通信"></a><a target="_blank" rel="noopener" href="https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V2/itc-with-emitter-0000001427584616-V2">emitter 线程间通信</a></h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Emitter主要用于主线程和Worker线程、Worker线程和Worker线程之间的事件同步。</span><br><span class="line">主要提供线程间发送和处理事件的能力，包括对持续订阅事件或单次订阅事件的处理、取消订阅事件、发送事件到事件队列等。</span><br><span class="line">emitter开发步骤主要分为两步：</span><br><span class="line">1、订阅事件</span><br><span class="line">2、发送事件</span><br></pre></td></tr></table></figure>
<h3 id="订阅事件"><a href="#订阅事件" class="headerlink" title="订阅事件"></a>订阅事件</h3><figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> emitter <span class="keyword">from</span> <span class="string">&quot;@ohos.events.emitter&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 定义一个eventId为1的事件</span></span><br><span class="line"><span class="keyword">let</span> event = &#123;</span><br><span class="line">    <span class="attr">eventId</span>: <span class="number">1</span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 收到eventId为1的事件后执行该回调</span></span><br><span class="line"><span class="keyword">let</span> <span class="title function_">callback</span> = (<span class="params">eventData</span>) =&gt; &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">info</span>(<span class="string">&#x27;event callback&#x27;</span>);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 订阅eventId为1的事件</span></span><br><span class="line">emitter.<span class="title function_">on</span>(event, callback);</span><br></pre></td></tr></table></figure>
<h3 id="发送事件"><a href="#发送事件" class="headerlink" title="发送事件"></a>发送事件</h3><figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> emitter <span class="keyword">from</span> <span class="string">&quot;@ohos.events.emitter&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 定义一个eventId为1的事件，事件优先级为Low</span></span><br><span class="line"><span class="keyword">let</span> event = &#123;</span><br><span class="line">    <span class="attr">eventId</span>: <span class="number">1</span>,</span><br><span class="line">    <span class="attr">priority</span>: emitter.<span class="property">EventPriority</span>.<span class="property">LOW</span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> eventData = &#123;</span><br><span class="line">    <span class="attr">data</span>: &#123;</span><br><span class="line">        <span class="string">&quot;content&quot;</span>: <span class="string">&quot;c&quot;</span>,</span><br><span class="line">        <span class="string">&quot;id&quot;</span>: <span class="number">1</span>,</span><br><span class="line">        <span class="string">&quot;isEmpty&quot;</span>: <span class="literal">false</span>,</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 发送eventId为1的事件，事件内容为eventData</span></span><br><span class="line">emitter.<span class="title function_">emit</span>(event, eventData);</span><br></pre></td></tr></table></figure>
<h2 id="worker-线程间通信"><a href="#worker-线程间通信" class="headerlink" title="worker 线程间通信"></a>worker 线程间通信</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">worker是与主线程并行的独立线程。创建Worker的线程被称为宿主线程，Worker工作的线程被称为Worker线程。创建Worker时传入的脚本文件在Worker线程中执行，通常在Worker线程中处理耗时的操作，需要注意的是，Worker中不能直接更新Page。</span><br></pre></td></tr></table></figure>
<ul>
<li>worker文件<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> worker, &#123; <span class="title class_">ThreadWorkerGlobalScope</span>, <span class="title class_">MessageEvents</span>, <span class="title class_">ErrorEvent</span> &#125; <span class="keyword">from</span> <span class="string">&#x27;@ohos.worker&#x27;</span>;</span><br><span class="line"><span class="keyword">const</span> <span class="attr">workerPort</span>: <span class="title class_">ThreadWorkerGlobalScope</span> = worker.<span class="property">workerPort</span>;</span><br><span class="line"></span><br><span class="line">workerPort.<span class="property">onmessage</span> = <span class="keyword">function</span> (<span class="params">e: MessageEvents</span>) &#123;</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">error</span>(<span class="string">&quot;这是worker1接收到的消息: &quot;</span>+<span class="title class_">JSON</span>.<span class="title function_">stringify</span>(e))</span><br><span class="line">  workerPort.<span class="title function_">postMessage</span>(<span class="string">&quot;这是worker1发送的消息&quot;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure></li>
<li>page文件<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> worker <span class="keyword">from</span> <span class="string">&#x27;@ohos.worker&#x27;</span>;</span><br><span class="line"> wk1 = <span class="keyword">new</span> worker.<span class="title class_">ThreadWorker</span>(<span class="string">&quot;entry/ets/workers/Worker1.ts&quot;</span>);</span><br><span class="line">   <span class="title function_">onPageHide</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="comment">// 根据业务按需停止worker线程</span></span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">wk1</span>.<span class="title function_">terminate</span>() </span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line"><span class="title function_">onPageShow</span>(<span class="params"></span>)&#123;</span><br><span class="line">  <span class="comment">// // 处理来自worker1线程的消息</span></span><br><span class="line">  <span class="variable language_">this</span>.<span class="property">wk1</span>.<span class="property">onmessage</span> = <span class="keyword">function</span> (<span class="params">message</span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">error</span>(<span class="string">&quot;主线程中打印来自worker1的消息： &quot;</span> + <span class="title class_">JSON</span>.<span class="title function_">stringify</span>(message))</span><br><span class="line">  &#125; </span><br><span class="line">&#125;</span><br><span class="line">  <span class="title function_">build</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="title class_">Column</span>() &#123;</span><br><span class="line">      <span class="title class_">Button</span>(<span class="string">&quot;主线程给 worker1发消息&quot;</span>).<span class="title function_">width</span>(<span class="string">&quot;100%&quot;</span>).<span class="title function_">onClick</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line"></span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">wk1</span>.<span class="title function_">postMessage</span>(<span class="string">&quot;主线程给 worker1 发送的消息&quot;</span>)</span><br><span class="line">      &#125;).<span class="title function_">margin</span>(&#123;<span class="attr">bottom</span>:<span class="number">15</span>&#125;)</span><br><span class="line">     </span><br><span class="line"></span><br><span class="line">    &#125;.<span class="title function_">width</span>(<span class="string">&#x27;100%&#x27;</span>).<span class="title function_">height</span>(<span class="string">&#x27;100%&#x27;</span>)</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure></li>
<li>build-profile.json5中配置的worker.ts的相对路径都为.&#x2F;src&#x2F;main&#x2F;ets&#x2F;workers&#x2F;worker.ts时，在Stage模型下创建worker需要传入路径entry&#x2F;ets&#x2F;workers&#x2F;worker.ts。</li>
<li>主线程和worker线程通信可以使用postMessage的方式相互通信，也可以使用emitter方式，工作线程与工作线程通信只能通过emitter方式进行通信。</li>
</ul>
<h1 id="eventhub-UIAbility组件与UI的数据同步"><a href="#eventhub-UIAbility组件与UI的数据同步" class="headerlink" title="eventhub UIAbility组件与UI的数据同步"></a>eventhub UIAbility组件与UI的数据同步</h1><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">EventHub提供了UIAbility组件/ExtensionAbility组件级别的事件机制，以UIAbility组件/ExtensionAbility组件为中心提供了订阅、取消订阅和触发事件的数据通信能力。基于发布订阅模式来实现，事件需要先订阅后发布，订阅者收到消息后进行处理。</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h2 id="page向uiability传递数据"><a href="#page向uiability传递数据" class="headerlink" title="page向uiability传递数据"></a>page向uiability传递数据</h2><ul>
<li><p>UiAbility</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="keyword">class</span> <span class="title class_">EntryAbility</span> <span class="keyword">extends</span> <span class="title class_ inherited__">UIAbility</span> &#123;</span><br><span class="line">  <span class="keyword">private</span> eventHub;</span><br><span class="line">  <span class="title function_">func1</span>(<span class="params">...data</span>) &#123;  <span class="comment">//解包，可变参数</span></span><br><span class="line">    <span class="comment">// 触发事件，完成相应的业务操作</span></span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">error</span>( <span class="string">&#x27;1. &#x27;</span> + <span class="title class_">JSON</span>.<span class="title function_">stringify</span>(data));</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="title function_">onCreate</span>(<span class="attr">want</span>: <span class="title class_">Want</span>, <span class="attr">launchParam</span>: <span class="title class_">AbilityConstant</span>.<span class="property">LaunchParam</span>): <span class="built_in">void</span> &#123;</span><br><span class="line">    <span class="comment">// 获得eventhub对象</span></span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">eventHub</span> = <span class="variable language_">this</span>.<span class="property">context</span>.<span class="property">eventHub</span></span><br><span class="line">    <span class="comment">// 订阅event_East事件</span></span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">eventHub</span>.<span class="title function_">on</span>(<span class="string">&quot;event_East&quot;</span>,<span class="variable language_">this</span>.<span class="property">func1</span>)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="title function_">onDestroy</span>(): <span class="built_in">void</span> &#123;</span><br><span class="line">    <span class="comment">// 取消订阅</span></span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">eventHub</span>.<span class="title function_">off</span>(<span class="string">&quot;event_East&quot;</span>)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="title function_">onWindowStageCreate</span>(<span class="attr">windowStage</span>: <span class="variable language_">window</span>.<span class="property">WindowStage</span>): <span class="built_in">void</span> &#123;</span><br><span class="line">    windowStage.<span class="title function_">loadContent</span>(<span class="string">&quot;pages/EventHubPage&quot;</span>, <span class="function">(<span class="params">err, data</span>) =&gt;</span> &#123;</span><br><span class="line">      <span class="keyword">if</span> (err.<span class="property">code</span>) &#123; </span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">      &#125; </span><br><span class="line">    &#125;);</span><br><span class="line">  &#125; </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>page</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Entry</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line">struct <span class="title class_">EventHubPage</span> &#123;</span><br><span class="line">  <span class="meta">@State</span> <span class="attr">message</span>: <span class="built_in">string</span> = <span class="string">&#x27;发送事件&#x27;</span></span><br><span class="line"></span><br><span class="line">  <span class="title function_">build</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="title class_">Row</span>() &#123;</span><br><span class="line"></span><br><span class="line">      <span class="title class_">Button</span>(<span class="variable language_">this</span>.<span class="property">message</span>)</span><br><span class="line">        .<span class="title function_">fontSize</span>(<span class="number">50</span>)</span><br><span class="line">        .<span class="title function_">fontWeight</span>(<span class="title class_">FontWeight</span>.<span class="property">Bold</span>)</span><br><span class="line">        .<span class="title function_">width</span>(<span class="string">&#x27;100%&#x27;</span>).<span class="title function_">onClick</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="title function_">getContext</span>(<span class="variable language_">this</span>).<span class="property">eventHub</span>.<span class="title function_">emit</span>(<span class="string">&quot;event_East&quot;</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="string">&quot;east&quot;</span>);</span><br><span class="line">      &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">    .<span class="title function_">height</span>(<span class="string">&#x27;100%&#x27;</span>)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ul>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="https://houyudong1989.gitee.io/blog">侯玉东</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="https://houyudong1989.gitee.io/blog/2024/03/25/harmonyOS/commonevent%E3%80%81eventhub%E3%80%81emitter%E5%92%8Cworker%E4%BD%BF%E7%94%A8/">https://houyudong1989.gitee.io/blog/2024/03/25/harmonyOS/commonevent%E3%80%81eventhub%E3%80%81emitter%E5%92%8Cworker%E4%BD%BF%E7%94%A8/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://houyudong1989.gitee.io/blog" target="_blank">East'blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/blog/tags/harmonyOS/">harmonyOS</a></div><div class="post_share"><div class="social-share" data-image="/blog/img/library1.jpeg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/blog/2024/03/29/harmonyOS/%E8%87%AA%E5%AE%9A%E4%B9%89%E5%A4%B4%E9%83%A8%E4%BB%A3%E7%A0%81%E6%B3%A8%E9%87%8A/" title="自定义头部代码注释"><img class="cover" src="/blog/img/library1.jpeg" onerror="onerror=null;src='/blog/img/friend_404.gif'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">自定义头部代码注释</div></div></a></div><div class="next-post pull-right"><a href="/blog/2024/03/22/harmonyOS/%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E4%BF%A1%E6%81%AF%E8%AF%BB%E5%8F%96/" title="配置文件信息读取"><img class="cover" src="/blog/img/library1.jpeg" onerror="onerror=null;src='/blog/img/friend_404.gif'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">配置文件信息读取</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/blog/2024/01/20/harmonyOS/ArkUI-X/" title="ArkUI-X"><img class="cover" src="/blog/img/library1.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2024-01-20</div><div class="title">ArkUI-X</div></div></a></div><div><a href="/blog/2023/12/15/harmonyOS/Canvas%E7%BB%98%E5%88%B6%E6%8A%98%E7%BA%BF%E5%9B%BE/" title="canvas绘制折线图"><img class="cover" src="/blog/img/library1.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-12-15</div><div class="title">canvas绘制折线图</div></div></a></div><div><a href="/blog/2023/12/02/harmonyOS/Canvas%E7%BB%98%E5%88%B6%E6%9F%B1%E7%8A%B6%E5%9B%BE/" title="canvas绘制柱状图"><img class="cover" src="/blog/img/library1.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-12-02</div><div class="title">canvas绘制柱状图</div></div></a></div><div><a href="/blog/2023/11/05/harmonyOS/hdc/" title="hdc 使用帮助"><img class="cover" src="/blog/img/library1.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-11-05</div><div class="title">hdc 使用帮助</div></div></a></div><div><a href="/blog/2023/12/26/harmonyOS/router%E8%B7%AF%E7%94%B1/" title="router路由跳转"><img class="cover" src="/blog/img/library1.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-12-26</div><div class="title">router路由跳转</div></div></a></div><div><a href="/blog/2024/03/21/harmonyOS/stage%E6%A8%A1%E5%9E%8B/" title="stage模型"><img class="cover" src="/blog/img/library1.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2024-03-21</div><div class="title">stage模型</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/blog/img/head.jpg" onerror="this.onerror=null;this.src='/blog/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">侯玉东</div><div class="author-info__description">生命不息，奋斗不止</div></div><div class="card-info-data site-data is-center"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">70</div></a><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">26</div></a><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">18</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/houyudong1989"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitee.com/houyudong1989" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a><a class="social-icon" href="mailto:420098321@qq.com" target="_blank" title="Email"><i class="fas fa-envelope" style="color: #4a7dbe;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">欢迎来到我的博客！！！</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#CES-common-event-service%EF%BC%88%E5%85%AC%E5%85%B1%E4%BA%8B%E4%BB%B6%E6%9C%8D%E5%8A%A1%EF%BC%89%E8%BF%9B%E7%A8%8B%E9%97%B4%E9%80%9A%E4%BF%A1"><span class="toc-number">1.</span> <span class="toc-text">CES common event service（公共事件服务）进程间通信</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%A4%BA%E6%84%8F%E5%9B%BE"><span class="toc-number">1.1.</span> <span class="toc-text">示意图</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%85%AC%E5%85%B1%E4%BA%8B%E4%BB%B6%E7%B1%BB%E5%9E%8B"><span class="toc-number">1.2.</span> <span class="toc-text">公共事件类型</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%97%A0%E5%BA%8F%E5%85%AC%E5%85%B1%E4%BA%8B%E4%BB%B6"><span class="toc-number">1.2.1.</span> <span class="toc-text">无序公共事件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%9C%89%E5%BA%8F%E5%85%AC%E5%85%B1%E4%BA%8B%E4%BB%B6"><span class="toc-number">1.2.2.</span> <span class="toc-text">有序公共事件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%B2%98%E6%80%A7%E5%85%AC%E5%85%B1%E4%BA%8B%E4%BB%B6"><span class="toc-number">1.2.3.</span> <span class="toc-text">粘性公共事件</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%85%AC%E5%85%B1%E4%BA%8B%E4%BB%B6%E5%8F%91%E5%B8%83"><span class="toc-number">1.3.</span> <span class="toc-text">公共事件发布</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%85%AC%E5%85%B1%E4%BA%8B%E4%BB%B6%E8%AE%A2%E9%98%85%E5%92%8C%E5%8F%96%E6%B6%88"><span class="toc-number">1.4.</span> <span class="toc-text">公共事件订阅和取消</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AF%BC%E5%85%A5%E6%A8%A1%E5%9D%97"><span class="toc-number">1.4.1.</span> <span class="toc-text">导入模块</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA%E8%AE%A2%E9%98%85%E8%80%85%E4%BF%A1%E6%81%AF%EF%BC%8C%E8%AE%A2%E9%98%85%E4%BD%95%E7%A7%8D%E4%BA%8B%E4%BB%B6"><span class="toc-number">1.4.2.</span> <span class="toc-text">创建订阅者信息，订阅何种事件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA%E8%AE%A2%E9%98%85%E8%80%85%EF%BC%8C%E7%94%A8%E4%BA%8E%E6%89%A7%E8%A1%8C%E8%AE%A2%E9%98%85%E3%80%81%E9%80%80%E8%AE%A2%E6%93%8D%E4%BD%9C"><span class="toc-number">1.4.3.</span> <span class="toc-text">创建订阅者，用于执行订阅、退订操作</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA%E8%AE%A2%E9%98%85%E5%9B%9E%E8%B0%83%E5%87%BD%E6%95%B0"><span class="toc-number">1.4.4.</span> <span class="toc-text">创建订阅回调函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8F%96%E6%B6%88%E8%AE%A2%E9%98%85%E4%BA%8B%E4%BB%B6"><span class="toc-number">1.4.5.</span> <span class="toc-text">取消订阅事件</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%BA%BF%E7%A8%8B%E9%97%B4%E9%80%9A%E4%BF%A1-emitter-%E5%92%8C-worker"><span class="toc-number">2.</span> <span class="toc-text">线程间通信 emitter 和 worker</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#emitter-%E7%BA%BF%E7%A8%8B%E9%97%B4%E9%80%9A%E4%BF%A1"><span class="toc-number">2.1.</span> <span class="toc-text">emitter 线程间通信</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%AE%A2%E9%98%85%E4%BA%8B%E4%BB%B6"><span class="toc-number">2.1.1.</span> <span class="toc-text">订阅事件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8F%91%E9%80%81%E4%BA%8B%E4%BB%B6"><span class="toc-number">2.1.2.</span> <span class="toc-text">发送事件</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#worker-%E7%BA%BF%E7%A8%8B%E9%97%B4%E9%80%9A%E4%BF%A1"><span class="toc-number">2.2.</span> <span class="toc-text">worker 线程间通信</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#eventhub-UIAbility%E7%BB%84%E4%BB%B6%E4%B8%8EUI%E7%9A%84%E6%95%B0%E6%8D%AE%E5%90%8C%E6%AD%A5"><span class="toc-number">3.</span> <span class="toc-text">eventhub UIAbility组件与UI的数据同步</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#page%E5%90%91uiability%E4%BC%A0%E9%80%92%E6%95%B0%E6%8D%AE"><span class="toc-number">3.1.</span> <span class="toc-text">page向uiability传递数据</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/blog/2024/05/06/c++/5%E3%80%81%E5%AD%97%E7%AC%A6%E5%92%8C%E5%AD%97%E7%AC%A6%E4%B8%B2/" title="字符和字符串"><img src="/blog/img/library1.jpeg" onerror="this.onerror=null;this.src='/blog/img/friend_404.gif'" alt="字符和字符串"/></a><div class="content"><a class="title" href="/blog/2024/05/06/c++/5%E3%80%81%E5%AD%97%E7%AC%A6%E5%92%8C%E5%AD%97%E7%AC%A6%E4%B8%B2/" title="字符和字符串">字符和字符串</a><time datetime="2024-05-06T11:15:27.280Z" title="发表于 2024-05-06 19:15:27">2024-05-06</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2024/05/06/c++/4%E3%80%81%E6%8C%87%E9%92%88%E5%92%8C%E5%87%BD%E6%95%B0%E6%8C%87%E9%92%88/" title="指针和函数指针"><img src="/blog/img/library1.jpeg" onerror="this.onerror=null;this.src='/blog/img/friend_404.gif'" alt="指针和函数指针"/></a><div class="content"><a class="title" href="/blog/2024/05/06/c++/4%E3%80%81%E6%8C%87%E9%92%88%E5%92%8C%E5%87%BD%E6%95%B0%E6%8C%87%E9%92%88/" title="指针和函数指针">指针和函数指针</a><time datetime="2024-05-06T11:14:29.047Z" title="发表于 2024-05-06 19:14:29">2024-05-06</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2024/05/05/python/7%E3%80%81m3u8%E8%A7%86%E9%A2%91%E6%A0%BC%E5%BC%8F/" title="m3u8格式"><img src="/blog/img/library1.jpeg" onerror="this.onerror=null;this.src='/blog/img/friend_404.gif'" alt="m3u8格式"/></a><div class="content"><a class="title" href="/blog/2024/05/05/python/7%E3%80%81m3u8%E8%A7%86%E9%A2%91%E6%A0%BC%E5%BC%8F/" title="m3u8格式">m3u8格式</a><time datetime="2024-05-05T01:43:26.865Z" title="发表于 2024-05-05 09:43:26">2024-05-05</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2024/04/30/android/charles%E5%AE%89%E5%8D%93%E6%89%8B%E6%9C%BA%E6%8A%93%E5%8C%85/" title="charles 抓包"><img src="/blog/img/library1.jpeg" onerror="this.onerror=null;this.src='/blog/img/friend_404.gif'" alt="charles 抓包"/></a><div class="content"><a class="title" href="/blog/2024/04/30/android/charles%E5%AE%89%E5%8D%93%E6%89%8B%E6%9C%BA%E6%8A%93%E5%8C%85/" title="charles 抓包">charles 抓包</a><time datetime="2024-04-30T06:49:29.279Z" title="发表于 2024-04-30 14:49:29">2024-04-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2024/04/26/python/13%E3%80%81playwright/" title="playwright"><img src="/blog/img/library1.jpeg" onerror="this.onerror=null;this.src='/blog/img/friend_404.gif'" alt="playwright"/></a><div class="content"><a class="title" href="/blog/2024/04/26/python/13%E3%80%81playwright/" title="playwright">playwright</a><time datetime="2024-04-26T07:30:36.069Z" title="发表于 2024-04-26 15:30:36">2024-04-26</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2024 By 侯玉东</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/blog/js/utils.js"></script><script src="/blog/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.umd.min.js"></script><div class="js-pjax"></div><div class="aplayer no-destroy" data-id="8873950678" data-server="netease" data-type="playlist" data-fixed="true" data-autoplay="true"> </div><script defer="defer" id="ribbon" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="false"></script><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-fluttering-ribbon.min.js"></script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-heart.min.js" async="async" mobile="false"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/metingjs/dist/Meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = ["head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show",".js-pjax"]

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener
  btf.removeGlobalFnEvent('pjax')
  btf.removeGlobalFnEvent('themeChange')

  document.getElementById('rightside').classList.remove('rightside-show')
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

  typeof disqusjs === 'object' && disqusjs.destroy()
})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()
})

document.addEventListener('pjax:error', e => {
  if (e.request.status === 404) {
    pjax.loadUrl('/blog/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>